# -*- coding:utf-8 -*-
from datetime import datetime
import json

from django.conf import settings
from rest_framework.exceptions import APIException
from Apps.System.ser.loginLogSer import LoginInfoSer
from Apps.common.fileUp.file import fileSave, fileDownload
from Apps.user.filter.userFilter import userFilter
from Apps.user.models import User
from django.contrib.auth.hashers import (
    check_password, is_password_usable, make_password,
)
from Apps.common.response import SuccessResponse, ErrorResponse
from Apps.util.jwt_util import JwtToken_create
from Apps.util.request_util import get_request_ip, get_login_location, get_browser, get_os, get_device, get_weather, \
    get_day_note
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from Apps.System.models.loginLog import SystemUserLoginInfo
from Apps.user.ser.userSer import UserSer
from captcha.models import CaptchaStore
from Apps.common.chart_request.e_chart import Chart
import logging

logger = logging.getLogger("django")

from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync

channel_layer = get_channel_layer()


# LoginMsg

def send_msg(user_id, text):
    async_to_sync(channel_layer.group_send)(user_id, {"type": "sendMsg", "text": text})


class LoginView(APIView):
    authentication_classes = []

    def code(self, request):

        if not settings.CAPTCHA_STATE:  # 未开启验证码则返回 True
            return True
        codeKey = request.data.get('codeKey', None)
        code = request.data.get('code', None)
        if not code:
            raise APIException(detail='无验证码')
        try:
            get_captcha = CaptchaStore.objects.get(hashkey=codeKey)
            if str(get_captcha.response).lower() == code.lower():  # 如果验证码匹配
                get_captcha.delete()
                return True
            # 开放code，方便测试
            if code.lower() == "789":
                if get_captcha:
                    get_captcha.delete()
                return True

            else:
                # 验证失败情况，删除数据库code
                if get_captcha:
                    get_captcha.delete()
                raise APIException(detail='验证码错误')
        except Exception:
            raise APIException(detail='验证码错误')

    def post(self, request, *args, **kwargs):
        # 校验验证码
        if not self.code(request):
            return ErrorResponse("验证码错误")

        # 校验用户名，密码
        username = request.data["username"]
        password = request.data["password"]
        try:
            if username == '' or password == '':
                raise ValueError("用户名或密码为空")
            user = User.objects.filter(username=username).first()
            if user is not None:
                check_result = user.check_password(password)
                if check_result:
                    user.last_login = datetime.now()
                    user.save()

                    token = JwtToken_create(user)

                    self.sava_login_info(request, user.id, username,
                                         msg="登陆系统", login_type="密码登陆", status='登陆成功',
                                         losePassword=password)

                    return SuccessResponse(
                        # data={"user": user.username, "token": token, "role": user.roles, "menu": ""},
                        data={"userid": user.id, "user": user.username, "token": token},
                        message="登陆成功")
        except ValueError as e:
            pass

        self.sava_login_info(request, "", username,
                             msg="登陆系统", login_type="密码登陆", status='登陆失败',
                             losePassword=password)
        return ErrorResponse(msg="登陆失败")

    def sava_login_info(self, request, userId, username, msg, login_type, status, losePassword):
        browser = get_browser(request)
        ipaddr = get_request_ip(request)
        device = get_device(request)
        os = get_os(request)
        location = get_login_location(request)

        login_info = SystemUserLoginInfo(userid=userId, username=username, browser=browser, ipaddr=ipaddr,
                                         device=device,
                                         loginLocation=location, msg=msg, os=os, status=status,
                                         login_type=login_type, losePassword=losePassword)
        login_info.save()


class getUserByCodeView(APIView):
    def post(self, request, *args, **kwargs):
        result = Chart().getLoginUserByCode(request.data.get("code", None))
        logger.info(f"扫码code调用企微后台返回的结果:{result}")

        return SuccessResponse("111")


class UserInfoView(APIView):

    def get(self, request, *args, **kwargs):
        serializer = UserSer(request.user)
        return SuccessResponse(serializer.data)


class CheckUserLogin(APIView):
    # 校验token
    def get(self, request, *args, **kwargs):
        return SuccessResponse("Success")


class LogoutView(APIView):
    """
    清除用户缓存
    """

    def post(self, request, *args, **kwargs):
        send_msg(request.user.id, "logout")
        return SuccessResponse("退出成功")


class userView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer
    filter_class = userFilter

    def create(self, request, *args, **kwargs):
        request.data["password"] = make_password("123456")
        request.data["corp_user"] = json.dumps(request.data["corp_user"])
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = serializer.save()
        # # 保存数据
        userId = instance.id
        roleIds = request.data["roles"]
        User.objects.get(id=userId).role_set.set(roleIds)
        return SuccessResponse("保存成功")

    def update(self, request, *args, **kwargs):
        instance = self.get_object()
        # 部分更新
        serializer = self.get_serializer(instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        instance = serializer.save()
        # # 保存数据
        userId = instance.id
        roleIds = request.data["roles"]
        User.objects.get(id=userId).role_set.set(roleIds)

        return SuccessResponse("更新成功")


class SaveAvatar(APIView):

    def post(self, request, *args, **kwargs):
        path = fileSave(request, "avatar")
        logger.info(path)
        return SuccessResponse(path)


class getIndexWeatherInfo(APIView):

    def get(self, request, *args, **kwargs):
        weather_dict = get_weather(request)
        response = {
            'province': weather_dict["province"],
            'city': weather_dict["city"],
            'area': weather_dict["area"],
            'dayIcon': weather_dict["data"]["dayIcon"],
            'dayWeather': weather_dict["data"]["dayWeather"],
            'dayTemp': weather_dict["data"]["dayTemp"],
            'nightTemp': weather_dict["data"]["nightTemp"],
        }

        return SuccessResponse(response)


class getDayNote(APIView):
    def get(self, request, *args, **kwargs):
        dayNote = get_day_note()
        # response = {
        #     'province': weather_dict["province"],
        #     'city': weather_dict["city"],
        #     'area': weather_dict["area"],
        #     'dayIcon': weather_dict["data"]["dayIcon"],
        #     'dayWeather': weather_dict["data"]["dayWeather"],
        #     'dayTemp': weather_dict["data"]["dayTemp"],
        #     'nightTemp': weather_dict["data"]["nightTemp"],
        # }

        return SuccessResponse(dayNote)


class getIndexUserInfo(APIView):
    def get(self, request, *args, **kwargs):
        user = request.user
        # roles = UserRole.objects.filter(user__id=user.id).all().values("role__roleName")
        loginInfo = SystemUserLoginInfo.objects.filter(userid=user.id).first()
        ser = LoginInfoSer(loginInfo)
        response = {
            'username': user.username,
            'name': user.name,
            'isSuper': user.is_superuser,
            # 'roles': roles,
            'create_time': ser.data["create_time"],
            'loginLocation': ser.data["loginLocation"],
        }

        return SuccessResponse(response)
